import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import { defineConfig, loadEnv } from 'vite'
import { viteMockServe } from 'vite-plugin-mock'
import { join } from 'path'
import vue from '@vitejs/plugin-vue'
import copyPlugin from 'rollup-plugin-copy'
import vueJsx from '@vitejs/plugin-vue-jsx'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
//引入svg需要用到的插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

function resolve(dir: string) {
  return join(__dirname, dir)
}

// https://vitejs.dev/config/
export default ({ command, mode }: { command: any; mode: any }) => {
  //获取环境变量mode:当前环境变量；process.cwd():当前文件目录；
  const env = loadEnv(mode, process.cwd() + '\\src', ['VITE', 'VUE'])
  console.log('环境变量:', env, env.VITE_SERVE)
  const isBuild = command === 'build'
  console.log('当前模式:', mode, '是否构建:', isBuild)
  // mode: 区分生产环境还是开发环境
  // process.cwd(): 获取当前文件的目录跟地址
  // loadEnv(): 返回当前环境env文件中额外定义的变量

  return defineConfig({
    //指定环境变量文件目录
    envDir: './src',
    // 环境变量前缀,默认只会暴露VITE开头变量，定义后可暴露VUE开头变量
    envPrefix: ['VITE', 'VUE'],
    //scss全局变量的一个配置
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: '@import "./src/styles/variable.scss";',
        },
      },
    },
    //插件配置
    plugins: [
      vue({
        template: {
          compilerOptions: {
            isCustomElement: (tag) => ['micro-app'].includes(tag),
          },
        },
      }),
      viteMockServe({
        //mockPath: 'mock',
        localEnabled: command === 'dev', //保证开发阶段可以使用mock接口
        //prodEnabled: command === 'build',
      } as any),
      //引入svg字体图标
      createSvgIconsPlugin({
        //指定需要缓存的图标目录
        iconDirs: [resolve('src/assets/icons')],
        //指定symbolId格式
        symbolId: 'icon-[dir]-[name]',
      }),
      // 引入vue-setup-extend插件
      VueSetupExtend(),
      vueJsx(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      // Components({
      //   resolvers: [ElementPlusResolver()],
      // }),
      // 复制配置文件
      copyPlugin({
        targets: [
          {
            src: 'env/' + mode + '.json', //根据打包命令中的环境参数，获取不同环境的配置文件
            dest: 'public', //本地运行时将配置文件复制到public目录下，打包时将对应文件复制到dist目录下
            rename: () => `config.json`, //重命名拷贝的文件
          },
        ],
      }),
    ],
    resolve: {
      //路径别名
      alias: {
        //'@': fileURLToPath(new URL('./src', import.meta.url))
        '@': resolve('src'),
        '@assets': resolve('src/assets'),
        '@components': resolve('src/components'),
        '@layout': resolve('src/layout'),
        '@public': resolve('public'),
        '@plugins': resolve('src/plugins'),
        '@scss': resolve('src/assets/scss'),
        '@hooks': resolve('src/hooks'),
        '@types': resolve('src/types'),
        '@views': resolve('src/views'),
        '@directive': resolve('src/directive'),
        '@utils': resolve('src/utils'),
      },
    },
    // 本地反向代理解决浏览器跨域限制
    server: {
      host: '0.0.0.0', // 允许外部访问
      port: 5000, // 端口号
      open: true, // 启动时是否打开浏览器
      cors: true, // 允许跨域
      //跨域代理
      proxy: {
        [env.VITE_APP_BASE_API]: {
          target: env.VITE_SERVE, //获取数据的服务器地址设置
          changeOrigin: true, //需要代理跨域
          rewrite: (path) => path.replace(/^\/api/, ''), //路径重写
        },
      },
      // 设置静态资源目录
      hmr: {
        overlay: false, // 禁用浏览器错误提示
      },
    },
    esbuild: {
      drop: isBuild && mode === 'production' ? ['console', 'debugger'] : [], // 禁用 console.log 和 debugger
    },
  })
}
